#include "Server.h"
#include "NetworkWrapper.h"

Server::Server()
        : serverSocket(NULL), currentId(1)
{
}

Server::~Server()
{
}

void Server::init()
{
    serverSocket = NetworkWrapper::openServerSocket();
}

void Server::mainLoop()
{
    TCPsocket socket = NetworkWrapper::acceptConnection(serverSocket);
    if (socket != NULL)
    {
        ServerMessageReceiverPtr msgReceiver(new ServerMessageReceiver(socket, currentId));
        msgReceiver->start();
        messageReceivers[currentId] = msgReceiver;
        currentId++;
    }
}

void Server::cleanUp()
{
    ServerMessageReceiverMap::iterator it;
    for (it = messageReceivers.begin(); it != messageReceivers.end(); ++it)
    {
        it->second->quit();
    }
    messageReceivers.clear();
    NetworkWrapper::closeSocket(serverSocket);
}

void Server::sendToClients(NetworkEvent& event)
{
    ServerMessageReceiverMap::iterator it;
    for (it = messageReceivers.begin(); it != messageReceivers.end(); ++it)
    {
        it->second->send(event.getMessageBlob(), event.getMessageBlobSize());
    }
}

void Server::sendToClient(NetworkEvent& event, long playerId)
{
    messageReceivers[playerId]->send(event.getMessageBlob(), event.getMessageBlobSize());
}

void Server::sendToClients(NetworkEvents& events)
{
    for (NetworkEvents::iterator it = events.begin(); it != events.end(); ++it)
    {
        if ((*it).second != -1)
        {
            sendToClient(*((*it).first), (*it).second);
        }
        else
            sendToClients(*((*it).first));
    }
}

void Server::removeClient(int id)
{
    ServerMessageReceiverMap::iterator it = messageReceivers.find(id);
    if (it != messageReceivers.end())
    {
        it->second->quit();
        messageReceivers.erase(it);
    }
}

unsigned int Server::getNrOfPlayers()
{
    return messageReceivers.size();
}
